package org.essilab.analyzer.Configuration;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * This class is used to read property files.
 *
 * @author Mohamed-Amine Chouchene, Ahcène Idinarere, Vincent Nock, Alain
 * Janin-Manificat
 */
public class FileLoader {

    boolean init = false;
    Properties props = new Properties();

    /**
     * Load a property file. Swith Config#init to true if the load success.
     *
     * @param filename - path of the property file to load.
     */
    public FileLoader(String filename) {
        try {
            FileInputStream fin = new FileInputStream(filename);
            InputStreamReader isr = new InputStreamReader(fin, "UTF8");
            props.load(isr);
            init = true;
            fin.close();
            isr.close();
        } catch (Exception e) {
            init = false;
            e.printStackTrace();
        }
    }

    /**
     * Return the property value of the given key.
     *
     * @param key String - key to look for in previously loaded property file.
     * @return String - If the key exist and a property file is loaded, return
     * the property value else return null.
     */
    private String get(String key) {
        if (init) {
            return props.getProperty(key);
        }
        return null;
    }

    /**
     * Return all the properties value of the loaded property file.
     *
     * @return List<String> - The list of all values in the loaded file.
     */
    public List<String> getAllValues() {
        List<String> values = new ArrayList<String>();
        for (Object key : props.keySet()) {
            String value = get((String) key).trim();
            if (!values.contains(value)) {
                values.add(value);
            }
        }
        return values;
    }
}
